package com.stlm2.util;


import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.stlm2.core.AppConfig;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.apache.commons.lang.BooleanUtils;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * Author: fuchunyu
 * Date: 2017/6/19
 * Description：fileInput上传专用接口
 */
public class UploadImage extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static String ImagePath="http://image.chinaddcat.com/";

	public static String getFilePath() {
		return "file/" + Convert.toShortYMDWithNoSplit(new Date()) + "/";
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		ServletOutputStream os = response.getOutputStream();

		String isDetail=request.getParameter("isDetail");

		/*
		*    oos需要的属性
		* */

		String endpoint = "http://oss-cn-beijing.aliyuncs.com";
		String accessKeyId = "LTAIrLdK8OYw20F7";
		String accessKeySecret = "KfH2x72p6zFxbfKqC3kECzwOwFnHAK";
		String bucketName = "ddw-image";
		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);


		String watermark="http://image.ddmzl.com/shuiyin2.png";

         /*
         *
         * */
		// 获得文件保存路径
	/*	String filePath = getFilePath();
		String path = getTempPath(filePath);
		*/

		// 临时文件目录
		File temp = new File("/usr/local/temp/upload/");
		if (!temp.exists())
			temp.mkdirs();

		// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload，工厂容量为50M
		DiskFileItemFactory factory = new DiskFileItemFactory(50 * 1024 * 1024, temp);
		// 用以上工厂实例化上传组件
		ServletFileUpload sfu = new ServletFileUpload(factory);
		// 单个文件最大值为8M
		sfu.setSizeMax(8* 1024 * 1024);

		List fileList = null;
		try {
			fileList = sfu.parseRequest(request);
		} catch (FileUploadException e) {
			if (e instanceof SizeLimitExceededException) {
				os.write("文件太大了".getBytes("UTF-8"));
				os.close();
				return;
			} else {
				os.write("未知异常".getBytes("UTF-8"));
				os.close();
				return;
			}
		}

		if (fileList == null || fileList.size() == 0) {
			os.write("请上传文件".getBytes("UTF-8"));
			os.close();
			return;
		}

		String fileNames = null;
		Iterator iter = fileList.iterator();
		while (iter.hasNext()) {
			FileItem item = (FileItem) iter.next();
			if (!item.isFormField()) {
				String fileName = item.getName();
				if(fileName.lastIndexOf('.') == -1){
					return;
				}
				String fileExt = fileName.substring(fileName.lastIndexOf('.'));
				if (!".png.jpg.jpeg.gif.bmp".contains(fileExt.toLowerCase())) {
					os.write("文件类型错误".getBytes("UTF-8"));
					os.close();
					return;
				}
				fileName = getFileName() + fileExt;
				BufferedImage bufImg=null;
				try {
					if(BooleanUtils.toBoolean(isDetail)){
						 bufImg = ImageMarkLogoByIcon.markImageByIcon(watermark,item);// 把图片读入到内存中
					}else {
						bufImg=ImageIO.read(item.getInputStream());
					}
					if(item.getSize()>1048576){
						bufImg = Thumbnails.of(bufImg).width(1024).keepAspectRatio(true).outputQuality(0.9).asBufferedImage();
					}
					ByteArrayOutputStream bos = new ByteArrayOutputStream();// 存储图片文件byte数组
					ImageIO.write(bufImg, "jpg", bos); // 图片写入到 ImageOutputStream
					InputStream input = new ByteArrayInputStream(bos.toByteArray());
					// 这里将图片上传到oos服务器上面服务器上面
					/*File file = File.createTempFile(fileName, fileExt);
					file.deleteOnExit();
					item.write(file);*/
					client.putObject(new PutObjectRequest(bucketName, fileName,input));
					//file.delete();


					//item.write(new File(path, fileName));
				} catch (Exception e) {
					client.shutdown();
					e.printStackTrace();
					continue;
				} finally {
            /*
             * Do not forget to shut down the client finally to release all allocated resources.
             */

					//client.shutdown();
				}
				//	fileName = AppConfig.RESOURCE_APP_ROOT + filePath + fileName;

				if (fileNames == null) {
					fileNames = ImagePath + fileName;
				}
				else {
					fileNames += "," + ImagePath + fileName;
				}
			}
		}
		os.write(("success" + "|" + fileNames).getBytes("UTF-8"));

		client.shutdown();
		os.close();
		return;
	}

	public static String getTempPath(String filePath) {
		String projectName = AppConfig.PROJECT_NAME;
		String ret = AppConfig.getResourceHome();
		String contextPath = AppConfig.getContextPath();
		if (!contextPath.equals(projectName) && ret.contains(projectName)) {
			ret = ret.substring(0, ret.indexOf(projectName) - 1);
		}
		String path = ret + AppConfig.RESOURCE_APP_ROOT + filePath;
		// 文件上传目录
		File sourceFile = new File(path);
		if (!sourceFile.exists()) {
			sourceFile.mkdirs();
		}
		return path;
	}

	/**
	 * 获取文件名
	 * UUID 拼接 8位日期
	 *
	 * 如需获得原图，可将图片名称截后六位即图片创建日期，然后到file文件夹下根据日期即可找到
	 * @return
	 */
	public static String getFileName(){
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String time = Convert.toShortYMDWithNoSplit(new Date());
		return uuid + time;
	}
}

